// codabar.js - 已改为 ES Module 格式，兼容 UniApp
import Barcode from "../Barcode.js"; // 确保路径正确，且 Barcode.js 也是 ES Module 版本

// codabar 编码器类，继承自 Barcode
export class codabar extends Barcode {
  constructor(data, options) {
    // 如果没有起止符，自动包裹 A...A
    let formattedData = data;
    if (data.search(/^[0-9\-\$\:\.\+\/]+$/) === 0) {
      formattedData = "A" + data + "A";
    }

    // 调用父类构造函数
    super(formattedData.toUpperCase(), options);

    // 显示文本去掉起止符 A/B/C/D
    this.text = this.options.text || this.text.replace(/[A-D]/g, '');
  }

  // 验证数据合法性
  valid() {
    return this.data.search(/^[A-D][0-9\-\$\:\.\+\/]+[A-D]$/i) !== -1;
  }

  // 编码生成二进制字符串
  encode() {
    const result = [];
    const encodings = this.getEncodings();

    for (let i = 0; i < this.data.length; i++) {
      const char = this.data.charAt(i).toUpperCase(); // 确保大写
      result.push(encodings[char]);

      // 除最后一个字符外，插入窄空格 "0"
      if (i !== this.data.length - 1) {
        result.push("0");
      }
    }

    return {
      text: this.text,
      data: result.join('')
    };
  }

  // Codabar 字符编码表
  getEncodings() {
    return {
      "0": "101010011",
      "1": "101011001",
      "2": "101001011",
      "3": "110010101",
      "4": "101101001",
      "5": "110101001",
      "6": "100101011",
      "7": "100101101",
      "8": "100110101",
      "9": "110100101",
      "-": "101001101",
      "$": "101100101",
      ":": "1101011011",
      "/": "1101101011",
      ".": "1101101101",
      "+": "101100110011",
      "A": "1011001001",
      "B": "1001001011",
      "C": "1010010011",
      "D": "1010011001"
    };
  }
}
